<template>
  <n-card title="博客文章" style="margin-bottom: 16px" class="markdown-body">
    <template #header-extra>
      <div class="goHome" @click="goHome">
        <router-link to="/">前台首页</router-link>
      </div>
    </template>
    <n-tabs v-model:value="tabVal" justify-content="space-evenly" type="line">
      <n-tab-pane name="list" tab="文章列表">
        <div v-for="(item, index) in ArticleOptions" :key="item.id" style="margin-bottom:15px">
          <n-card :title="item.title" embedded :bordered="false">
            {{ item.content }}
            <template #footer>
              <n-space align="baseline">
                <div class="publish_time">发布时间：{{ dayjs(item.createdAt).format('YYYY-MM-DD HH:MM:ss') }}</div>
                <n-button class="updateArticle" @click="handleUpdate(item)">修改</n-button>
                <n-button class="delArticle" @click="delArticle(item.id)">删除</n-button>
              </n-space>
            </template>
          </n-card>
        </div>
      </n-tab-pane>
      <n-tab-pane name="add" tab="添加文章">

        <n-form>
          <n-form-item label="标题">
            <n-input v-model:value="addArticle.title" placeholder="请填写标题" />
          </n-form-item>
          <n-form-item label="内容">
            <!-- <n-input v-model:value="addArticle.content" /> -->
            <rich-text-editor v-model="addArticle.content"></rich-text-editor>
          </n-form-item>
          <n-form-item>
            <n-button @click="handleAdd">提交</n-button>
          </n-form-item>
        </n-form>

      </n-tab-pane>
      <n-tab-pane name="update" tab="修改文章">
        <n-form>
          <n-form-item label="修改标题">
            <n-input v-model:value="updateArticle.title" placeholder="请填写标题" />
          </n-form-item>
          <!-- <n-form-item label="标签">
            <n-select v-model:value="addArticle.selected" :options="ArticleOptions" />
          </n-form-item> -->
          <n-form-item label="修改内容">
            <rich-text-editor v-model="updateArticle.content"></rich-text-editor>
          </n-form-item>
          <n-form-item>
            <n-button @click="handleCommit">提交</n-button>
          </n-form-item>
        </n-form>
      </n-tab-pane>
    </n-tabs>
  </n-card>
  <n-pagination v-model:page="page" v-model:page-size="pageSize" :page-count="90" show-size-picker
    :page-sizes="pageSizes" @click="handlePage()" />
  <!-- {{ addArticle.content }} -->
</template>

<script setup>
import { NCard, NTabs, NTabPane, NForm, NFormItem, NInput, NSelect, NButton, NSpace, NPagination } from 'naive-ui'
import { reactive, onMounted, ref, inject } from 'vue';
import RichTextEditor from '../../../components/RichTextEditor.vue'
const axios = inject('axios')
const dayjs = inject('dayjs')
const message = inject('message')
const dialog = inject('dialog')
const tabVal = ref('list')
// 添加文章初始化变量
const addArticle = reactive({
  // selected: '请选择',
  title: '',
  content: '',
  author_id: ''
})
// 修改文章的初始化变量
const updateArticle = reactive({
  title: '',
  content: '',
})
const ArticleOptions = ref([])
onMounted(() => {
  loadArticleData(page.value, pageSize.value)
})

// 发布文章
const handleAdd = async () => {
  const result = await axios.post('/api/articles', {
    data: {
      title: addArticle.title,
      content: addArticle.content
    }
  })
  if (result.status === 200) {
    addArticle.title = addArticle.content = ''
    tabVal.value = 'list'
    message.success('发布成功')
    loadArticleData(page.value, pageSize.value)
  }
  console.log(result);
}
// 修改文章
const handleUpdate = (item) => {
  tabVal.value = 'update'
  console.log('修改文章', item);
  updateArticle.title = item.title
  updateArticle.content = item.content
  updateArticle.articleId = item.id

}
// 修改文章
const handleCommit = async () => {
  const result = await axios.patch(`/api/articles/${updateArticle.articleId}`, {
    data: {
      title: updateArticle.title,
      content: updateArticle.content
    }
  })
  console.log('修改', result);
  if (result.status === 200) {
    message.success('文章修改成功')
    updateArticle.title = updateArticle.content = ''
    loadArticleData(page.value, pageSize.value)
    tabVal.value = 'list'

  } else {
    message.error('文章修改失败')
  }
}
// 分页
const page = ref(0)
const pageSize = ref(3)
const pageSizes = [
  {
    label: "3 每页",
    value: 3
  },
  {
    label: "4 每页",
    value: 4
  },
  {
    label: "5 每页",
    value: 5
  },
  {
    label: "6 每页",
    value: 6
  }
];
// 请求所有文章
const loadArticleData = async (pageVal, pageSizeVal) => {
  const result = await axios.get('/api/articles/all', {
    params: {
      page: pageVal,
      pagesize: pageSizeVal,
      author_id: localStorage.getItem('uid')
    }
  })
  // console.log('分类', result.data.data);
  // addArticle.uid = result.data.data.author
  // addArticle.value = result.data.data.map(item => {
  //   // addArticle.uid = item.author._id
  //   return {
  //     label: item.title,
  //     value: item.id
  //   }
  // })
  ArticleOptions.value = result.data.data
  if (result.data.data.length < pageSize.value) {
    message.warning('这是最后一页啦,往后没有数据啦')

  }
  console.log('所有文章分类', ArticleOptions.value);
}
// 处理分页函数
const handlePage = () => {
  console.log('当前页码和条数', page.value, pageSize.value);
  loadArticleData((page.value - 1) * pageSize.value, pageSize.value)
}
// 删除文章
const delArticle = (art_id) => {
  dialog.warning({
    title: '警告',
    content: '是否删除',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await axios.delete('/api/articles/' + art_id)
      // console.log('删除文章',result);
      if (result.status === 200) {
        message.success('文章删除成功')
        loadArticleData(page.value, pageSize.value)
      } else {
        message.error('文章删除失败')
      }
    },
    onNegativeClick: () => {
      message.error('已取消')
    }
  })

}
</script>

<style lang="scss" scoped>
a:hover {
  color: rgb(181, 179, 179);
  cursor: pointer;
  text-decoration: none;
}
</style>